<?php
namespace Home\Controller;

use Common\Model\ActivityModel;
use Home\Model\GoodsModel;
use Think\Controller;

/**
 * 商品列表
 * Class GoodsController
 * @package Home\Controller
 */
class GoodsListController extends BaseController
{

    public $local_id; // 店铺id

    use ActivityModel;

    public function __construct()
    {
        parent::__construct();
        $this->local_id = I('local_id');
    }

    /**
     * 商品列表
     */
    public function index()
    {
        $cat_id = I('category_id', '', intval());
//查询店铺信息
        $storeData = M('webpos_local_store')->where(['local_id'=>$this->local_id])->find();

//        $b2c_store_cat = M('b2c_store_cat');
//
//        $where = [
//            'store_cat_id' => $cat_id,
//            'local_id' => $this->local_id
//        ];
        // 查询分类信息
//        $store_cat_msg = $b2c_store_cat->where($where)->find();

        // 判断1为父级分类，2为子分类
/*        if ($store_cat_msg['level'] == 1) {
            $this->levelOne($cat_id);
        } elseif (($store_cat_msg['level'] == 2)) {
            $this->levelTwo($cat_id);
        }*/

        $this->assign([
            'cat_id' => $cat_id,
            'storeData' => $storeData,
            'local_id' => $this->local_id
        ]);
        $this->display();
    }

    public function ajax(){
        $cat_id = I('category_id', '', intval());

        $b2c_store_cat = M('b2c_store_cat');

        $where = [
            'store_cat_id' => $cat_id,
            'local_id' => $this->local_id
        ];
        // 查询分类信息
        $store_cat_msg = $b2c_store_cat->where($where)->find();

        // 判断1为父级分类，2为子分类
        if ($store_cat_msg['level'] == 1) {
            $this->levelOne($cat_id);
        } elseif (($store_cat_msg['level'] == 2)) {
            $this->levelTwo($cat_id);
        }
    }

    /**
     * 一级分类
     * @param $cat_id
     */
    public function levelOne($cat_id){

        $where = [];
        $order = $this->sort(); // 排序

        // 筛选条件
        $select = I('select', '', intval());
        if ($select) {
            if ($this->select()) {
                $where['a.store_pid'] = ['in', $this->select()];
            } else {
                echo json_encode([
                    'data' => 0,
                    'store_cat_msg' => 0,
                    'totalPage' => 0, // 总页数
                    'count' => 0, // 总个数
                    'page' => 0, // 第几页
                ]);
                exit;
            }
        }

        $b2c_store_cat = M('b2c_store_cat');
        // 查询子分类
        $store_cat_msg = $b2c_store_cat->where(['parent_id' => $cat_id, 'local_id' => $this->local_id])->select();

        // 将分类id数组重组字符串
        $arr_cat_id[] = $cat_id;
        foreach ($store_cat_msg as $v) {
            $arr_cat_id[] = $v['store_cat_id'];
        }
        $arr_cat_id = implode(',', $arr_cat_id);

        // 商品分页
        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 10);

        $where['a.scate_id'] = ['in', $arr_cat_id];
        $where['a.local_id'] = $this->local_id;
        $where['a.store_status'] = 'true'; // 店铺上架的商品

        $b2c_store_product = M('b2c_store_product a');
        $count = $b2c_store_product->join(C('DB_PREFIX').'b2c_products b on a.product_id = b.product_id and b.disabled = "false"', 'left')
            ->where($where)
            ->count();

/*        $Page = new \Think\Page($count, $num);
        $Page->setConfig('next','加载更多>>>');
        $Page->setConfig('theme','%DOWN_PAGE%');
        $show = $Page->show();*/

        $productMsg = $b2c_store_product->join(C('DB_PREFIX').'b2c_products b on a.product_id = b.product_id and b.disabled = "false"', 'left')
            ->field('a.*,b.name,b.spec_info')
            ->where($where)
            ->page($page, $num)
            ->order($order)
            ->select();

        //商品促销判定
        $this->GoodsPromotion($productMsg, $this->local_id);
/*        $this->assign([
            'productMsg' => $productMsg,
            'show' => $show,
            'store_cat_msg' => $store_cat_msg,
            'select' => $select
        ]);*/
        $totalPage = ceil($count/$num); // 总页面数
        $GoodsModel = new GoodsModel();

        foreach ($productMsg as  $k=>&$v) {
            $v['image'] = getThumb($v['goods_id']);

            // 判断闪购
            $flashGoods = $GoodsModel->checkGoodsIsStarBuy($v['store_pid']);
            if (!empty($flashGoods)) {
                $productMsg[$k]['flashPrice'] = $flashGoods['promotion_price'];
                $productMsg[$k]['store'] = $flashGoods['initnum'];
                $productMsg[$k]['freez'] = 0;
            }else{
                $productMsg[$k]['flashPrice'] = '';
            }
            // 判断组合促销
            $checkProductIsGroupPromotion = checkProductIsGroupPromotion($v['store_pid'], $v['local_id']);
            $productMsg[$k]['groupPromotion'] = $checkProductIsGroupPromotion;

        }

        echo json_encode([
            'data' => $productMsg,
            'store_cat_msg' => $store_cat_msg,
            'totalPage' => $totalPage, // 总页数
            'count' => $count, // 总个数
            'page' => $page, // 第几页
        ]);
    }

    /**
     * 二级分类
     */
    public function levelTwo($cat_id){

        $order = $this->sort(); // 排序

        $where = [];

        // 筛选条件
        $select = I('select', '', intval());
        if ($select) { // 套餐
            if ($this->select()) {
                $where['a.store_pid'] = ['in', $this->select()];
            } else {
                echo json_encode([
                    'data' => 0,
                    'store_cat_msg' => 0,
                    'totalPage' => 0, // 总页数
                    'count' => 0, // 总个数
                    'page' => 0, // 第几页
                ]);
                exit;
            }
        }

        // 商品分页
        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 10);

        $where['a.scate_id'] = ['in', $cat_id];
        $where['a.store_status'] = 'true';
        $where['a.local_id'] = $this->local_id;

        $b2c_store_product = M('b2c_store_product a');
        $count = $b2c_store_product->join(C('DB_PREFIX').'b2c_products b on a.product_id = b.product_id and b.disabled = "false"', 'left')
            ->where($where)
            ->count();

/*        $Page = new \Think\Page($count, $num);
        $Page->setConfig('next','加载更多>>>');
        $Page->setConfig('theme','%DOWN_PAGE%');
        $show = $Page->show();*/

        $productMsg = $b2c_store_product->join(C('DB_PREFIX').'b2c_products b on a.product_id = b.product_id and b.disabled = "false"', 'left')
            ->field('a.*,b.name,b.spec_info')
            ->where($where)
            ->page($page, $num)
            ->order($order)
            ->select();

        //商品促销判定
        $this->GoodsPromotion($productMsg, $this->local_id);

        $GoodsModel = new GoodsModel();
        foreach ($productMsg as $k=>$v) {
            // 判断闪购
            $flashGoods = $GoodsModel->checkGoodsIsStarBuy($v['store_pid']);
            if (!empty($flashGoods)) {
                $productMsg[$k]['flashPrice'] = $flashGoods['promotion_price'];
                $productMsg[$k]['store'] = $flashGoods['initnum'];
                $productMsg[$k]['freez'] = 0;
            }else{
                $productMsg[$k]['flashPrice'] = '';
            }
            // 判断组合促销
            $checkProductIsGroupPromotion = checkProductIsGroupPromotion($v['store_pid'], $v['local_id']);
            $productMsg[$k]['groupPromotion'] = $checkProductIsGroupPromotion;
        }


        $totalPage = ceil($count/$num); // 总页面数

        foreach ($productMsg as &$v) {
            $v['image'] = getThumb($v['goods_id']);
//            $v['label_info'] = getProductLabel($v['local_id'], $v['product_id']);
        }
        echo json_encode([
            'data' => $productMsg,
            'totalPage' => $totalPage, // 总页数
            'count' => $count, // 总个数
            'page' => $page, // 第几页
        ]);
    }

    /**
     * 获取排序
     * @return array
     */
    public function sort(){
        $sort = I('sort', '', intval());
        if (empty($sort)) {
            $sort = 1;
        }
        switch ($sort)
        {
            case 1:
                $order = ['a.store_pid' => 'desc'];// 默认排序
                break;
            case 2:
                $order = ['a.sales_num' => 'desc'];// 销量
                break;
            case 3:
                $order = ['a.grade' => 'desc'];// 评价
                break;
            case 4:
                $order = ['a.price' => 'desc'];// 价格最高
                break;
            case 5:
                $order = ['a.price' => 'asc'];// 价格最低
                break;
            default:
                $order = ['a.store_pid' => 'desc'];// 默认排序
        }
        $this->assign(['sort' => $sort]);
        return $order;
    }

    /**
     * 筛选
     */
    public function select(){
        $select = I('select', '', intval());
        if ($select == 1) { // 促销
            return $this->cuxiao();
        }
        if ($select == 2) { // 套餐
            return $this->group();
        }


    }

    /**
     * 查询套餐数据
     * @return string
     */
    public function group(){
        $time = time();
        $m = M('b2c_store_promotion_group a');
        $group = $m->join(C('DB_PREFIX').'b2c_store_promotion_group_item b on a.id = b.group_id')
            ->where(['a.state' => '1', 'a.local_id' => $this->local_id, "a.start_time <  {$time}", "a.end_time >  {$time}"])
            ->select();
//        echo $m->_sql();
        if ($group) {
            foreach ($group as $v) {
                $arr[] = $v['sp_id'];
            }
            return implode(',', $arr);
        }else {
            return false;
        }
    }

    /**
     * 查询促销
     * SELECT
     *
    FROM
    sdb_starbuy_flashsales_time sft
    LEFT JOIN `sdb_starbuy_flashsales_goods` sfg ON sft.tid = sfg.tid
    WHERE
    sft.`begin_time` <
    AND sft.`end_time` >
     */
    public function cuxiao(){
        $time = time();

        // 查询闪购商品
        $res = M('starbuy_flashsales_time a')
            ->join(C('DB_PREFIX').'starbuy_flashsales b ON a.special_id = b.special_id AND b.local_id = '.$this->local_id, 'left')
            ->join(C('DB_PREFIX').'starbuy_flashsales_goods c ON a.tid = c.tid', 'left')
            ->where(['a.begin_time' => ['LT' ,$time], 'a.end_time' => ['GT', $time], 'b.is_start' => '1'])
            ->select();
//echo M('starbuy_flashsales_time a')->_sql();
        if ($res) {
            foreach ($res as $v) {
                $arr[] = $v['store_pid'];
            }
            return implode(',', $arr);
        }else {
            return false;
        }
    }
}